<?php

namespace app\api\model\house;

use app\admin\model\Complain;
use app\common\model\User;
use think\Model;
use traits\model\SoftDelete;


class HouseOrderComplain extends Model
{


    use SoftDelete;


    // 表名
    protected $name = 'house_order_complain';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text'
    ];


    public function getStatusList()
    {
        return ['0' => __('处理中'), '1' => __('已完成'), '2' => __('已撤回')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }

    //详情
    public function info($complain_id)
    {
        $info = HouseOrderComplain::get($complain_id);

        $order_info = HouseOrder::where(['order_id'=>$info['order_id']])
            ->field('order_id,user_id,house_title,order_type_name,pay_money,checkin_date,leave_date')
            ->find();

        $user_info = User::where(['id'=>$order_info['user_id']])->field('nickname,avatar')->find();

        $dispose_list = HouseOrderComplainReply::where(['complain_id'=>$complain_id])
            ->order('createtime asc')
            ->select();

        $data = [
            'order_info'=>$order_info,
            'user_info'=>$user_info,
            'dispose_list'=>$dispose_list
        ];

        return $data;
    }


    //投诉页展示信息
    public function complainData($order_id)
    {
        $order_info = HouseOrder::where(['order_id'=>$order_id])
            ->field('order_id,user_id,house_title,order_type_name,pay_money,checkin_date,leave_date')
            ->find();

        $user_info = User::where(['id'=>$order_info['user_id']])->field('nickname,avatar')->find();

        $list = Complain::where(['type'=>1])->order('weigh desc')->column('name');

        $data = [
            'order_info'=>$order_info,
            'user_info'=>$user_info,
            'reason'=>$list
        ];

        return $data;
    }


    //投诉
    public function complain($order_id,$reason,$explain,$images,$user_id)
    {
        $info = HouseOrderComplain::get(['order_id'=>$order_id,'user_id'=>$user_id]);
        $order_info = HouseOrder::get($order_id);
        if ($info) throw new \Exception('该订单已投诉');
        if (empty($reason)) throw new \Exception('请选择投诉原因');
        if (empty($explain)) throw new \Exception('请填写补充说明');

        $model = new HouseOrderComplain();

        $data = [
            'order_id'=>$order_id,
            'user_id'=>$user_id,
            'owner_id'=>$order_info['owner_id'],
            'order_no'=>$order_info['order_no'],
            'reason'=>$reason,
            'explain'=>$explain,
            'images'=>$images
        ];

        $res = $model->save($data);

        return $res;
    }


}
